﻿using System;
using System.Reflection;
using BusinessLayer.Attributes;

namespace BusinessLayer.Tools
{
    /// <summary>
    /// Helper class for getting additional description fo enum member
    /// </summary>
    public class EnumsExtender
    {
        /// <summary>
        /// Gets the value of <see cref="DescriptionAttribute"/>.
        /// </summary>
        /// <param name="en">Enum value.</param>
        /// <returns>Description</returns>
        public static string GetDescription(Enum en)
        {
            return GetValueFromExtensionAttribute<DescriptionAttribute>(en);
        }

        /// <summary>
        /// Gets the value of <see cref="BuildConfigurationAttribute"/>.
        /// </summary>
        /// <param name="en">Enum value.</param>
        /// <returns>Build configuration name.</returns>
        public static string GetConfiguration(Enum en)
        {
            return GetValueFromExtensionAttribute<BuildConfigurationAttribute>(en);
        }

        /// <summary>
        /// Generic method for getting value of <see cref="BaseEnumExtenderAttribute"/>.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="en">Enum value.</param>
        /// <returns>Attributes value.</returns>
        private static string GetValueFromExtensionAttribute<T>(Enum en) where T:BaseEnumExtenderAttribute
        {
            Type type = en.GetType();

            MemberInfo[] memInfo = type.GetMember(en.ToString());

            if (memInfo.Length > 0)
            {

                object[] attrs = memInfo[0].GetCustomAttributes(typeof(T),
                    false);

                if (attrs.Length > 0)

                    return ((T)attrs[0]).Text;
            }
            return en.ToString();
        }
    }
}
